package com.ldk.base.framework.util.sms;

import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;

import com.ldk.base.framework.util.EncryptUtil;
import com.ldk.base.framework.util.HttpUtil;
import com.ldk.base.framework.util.SystemUtil;

/**
 * 集信通短信API
 * @author xiangwl
 *
 */
public class JxtSmsApi implements ISmsApi {
	/**
	 * 集信通短信模块
	 * @author xiangwl
	 *
	 */
	public enum JxtSmsTemplete{
		/**
		 * 验证码
		 */
		Templete13("验证码", 13, "13|手机号|验证码"),
		;
		private JxtSmsTemplete(String name, int templeteId, String formate){
			this.name = name;
			this.templeteId = templeteId;
			this.formate = formate;
		}
		private String name;
		private int templeteId;
		private String formate;
		/**
		 * 短信模版名称
		 * @return
		 */
		public String getName() {
			return name;
		}
		/**
		 * 短信模块ID
		 * @return
		 */
		public int getTempleteId() {
			return templeteId;
		}
		/**
		 * 短信模版参数格式 13|手机号|验证码
		 * @return
		 */
		public String getFormate() {
			return formate;
		}
	}

	private final String smsUrl = "http://218.201.202.174:8900/smstemp/http/sendSms?account=%s&reqNo=%s&authCode=%s&serviceCode=%s&msisdn=%s&content=%s&msgType=0";

	@Override
	public Boolean send(SmsConfig config) {
		if(config == null) return false;
		if(StringUtils.isBlank(config.getAccessKey()) ||
		   StringUtils.isBlank(config.getAccessPwd()) ||
		   StringUtils.isBlank(config.getPhonNos()) ||
		   StringUtils.isBlank(config.getContent()))
			return false;
		
		String account = config.getAccessKey();// "1001";
		String reqNo = SystemUtil.generateSn("");
		//pwd+reqNo
		String authCode= EncryptUtil.md5("alltopcn"+reqNo);
		String serviceCode = config.getAccessPwd();// "1065705400001";
		//发送内容要进行UTF－8编码一下
		String encodeContent = config.getContent();
		try{
			encodeContent = URLEncoder.encode(config.getContent(), "utf-8");
		}
		catch(Exception e){
			
		}
		String url = String.format(smsUrl, account, reqNo, authCode, serviceCode, config.getPhonNos(), encodeContent);
		
		String response = HttpUtil.post(url, null, null);
		String[] results = StringUtils.isEmpty(response) ? null : response.split(",");
		if(results != null && 
		   results.length > 0 && 
		   "result=0".equalsIgnoreCase(results[0])){
			return true;
		}
		return false;
	}
}
